#!/usr/bin/python
# -*- coding: utf-8 -*-

##
 # Copyright 2009 Caio Souza
 # This file is part of Rpyg.
 #
 # Rpyg is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # Rpyg is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with Rpyg. If not, see <http://www.gnu.org/licenses/>.
 ##

'''Módulo para a classe de controle local dos personagens.'''

import pygame

from rpyg.State import *
from rpyg.Controller import *

class Joystick(Controller):
    '''Classe de controle local dos personagens.'''

    registered_keys = {}
    '''Dicionario indexado por teclas apontando para o controle que a usa.'''

    def __init__(self, **k_args):
        '''Cria um controle local a partir das teclas passadas.'''

        Controller.__init__(self)

        self._moves = []
        '''Lista de teclas pressionadas.'''

        keys = {}

        keys[k_args['north']] = KEY_NORTH
        keys[k_args['east']] = KEY_EAST
        keys[k_args['south']] = KEY_SOUTH
        keys[k_args['west']] = KEY_WEST
        keys[k_args['act']] = KEY_ACT

        self._keys = keys
        '''Dicionário de teclas do joystick.'''

        self._register(k_args)

    def _register(self, keys):
        '''Registra as teclas que esse controle irá usar.'''

        rk = self.registered_keys

        n = keys['north']
        e = keys['east']
        s = keys['south']
        w = keys['west']
        a = keys['act']

        if rk.get(n) is None: rk[n] = []
        if rk.get(e) is None: rk[e] = []
        if rk.get(s) is None: rk[s] = []
        if rk.get(w) is None: rk[w] = []
        if rk.get(a) is None: rk[a] = []

        rk[n].append(self)
        rk[e].append(self)
        rk[s].append(self)
        rk[w].append(self)
        rk[a].append(self)

        self.act = False

    def pressed(self, key):
        '''Pressiona uma tecla do controle.'''

        key = self._keys[key]

        if key == KEY_ACT:
            self.act = True
            return

        with self._lock:
            if not len(self._moves): self._moves.append(key)
            elif len(self._moves) > 1: self._moves.insert(2, key)
            else:
                m = self._moves[0]
                we = KEY_WEST, KEY_EAST
                ns = KEY_NORTH, KEY_SOUTH
                if (key in we and m in ns) or (key in ns and m in we): self._moves.insert(0, key)
                else: self._moves.insert(2, key)

    def released(self, key):
        '''Solta uma tecla do controle.'''

        key = self._keys[key]

        if key == KEY_ACT:
            self.act = False
            return

        with self._lock:
            try: self._moves.remove(key)
            except ValueError: pass

    def get(self, i, j):
        '''Retorna a ação tomada pelo personagem.'''

        if self.act:
            self.act = False
            return State(KEY_ACT)

        with self._lock: moves = self._moves
        if not len(moves): return State(DO_NOTHING)

        state = MOVE_KEY
        key = moves[0]

        if self._tilemap.isBlocked(i, j, key):
            if len(moves) > 1:
                key = moves[1]
                if self._tilemap.isBlocked(i, j, key):
                    state = LOOK_AT
                    key = moves[0]
            else:
                state = LOOK_AT
                key = moves[0]

        return State(state, key = key)

    def moved(self):
        '''Confirma a movimentacao do personagem.'''


    def setMapPos(self, x, y):
        '''Atualiza a posição no mapa do jogo.'''

        self._tilemap.setPlayerPos(x, y)

